package com.service.user;

import com.controller.user.request.UserRequest;
import com.controller.user.response.UserResponse;
import com.core.contant.BusinessExceptionCode;
import com.core.contant.DataOperationConstants;
import com.mapper.UserMapper;
import com.model.User;
import com.service.BaseService;
import com.service.RedisService;
import com.service.user.constructor.UserConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by dawn on 2017/11/3.
 */
@Service
public class UserService extends BaseService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserConstructor userConstructor;

    @Transactional
    public UserResponse login(String name, String password) {
        UserResponse response = new UserResponse();
        // 查询是否有缓存
        String key = userConstructor.md5encrypt(name, password);
        Object obj = redisService.get(name);
        if (obj.equals(key)) {
            User user = checkLogin(name, password);
            // 登录成功设置redis缓存
            boolean flag = redisService.set(user.getName(), user.getPassword());
            response.setUser(user);
        }

        return response;
    }


    @Transactional
    public UserResponse registe(UserRequest request) {
        UserResponse response = new UserResponse();
        String name = request.getName();
        if (!checkName(name)) {
            throw buildBusinessException(BusinessExceptionCode.USERS_NAME_IS_EXISTING);
        }

        User user = userConstructor.constructUser(request);
        int id = userMapper.insert(user);
        if (DataOperationConstants.ADD_ONE_SUCCESS != id) {
            throw buildBusinessException(BusinessExceptionCode.USERS_REGISTE_DEFEATED);
        }
        response.setUser(user);
        return response;
    }

    @Transactional
    public UserResponse update(UserRequest request) {
        UserResponse response = new UserResponse();
        User user = userConstructor.constructUser(request);
        int cout = userMapper.updateByName(user);
        if (DataOperationConstants.UPDATE_ONE_SUCCESS != cout) {
            throw buildBusinessException(BusinessExceptionCode.USERS_UPDATE_DEFEATED);
        }
        response.setUser(user);
        // 修改账号密码
        return response;
    }


    public User checkLogin(String name, String password) {
        String key = userConstructor.md5encrypt(name, password);
        // 判断账号密码是否匹配
        User user = userMapper.checkLogin(name, key);
        if (null == user) {
            throw buildBusinessException(BusinessExceptionCode.USERS_NOT_EXIST);
        }
        return user;
    }

    private Boolean checkName(String name) {
        int cout = userMapper.selectByName(name);
        return DataOperationConstants.NOT_HAS_DATA == cout;
    }

}
